# $Id: data.py 14 2008-08-21 21:31:25Z jkingry $

from datetime import datetime

from google.appengine.ext import db
from google.appengine.api import users

def generate_string(length=16):
  import string
  import random
  d = [random.choice(string.letters + string.digits) for x in xrange(length)]
  s = "".join(d)
  return s
  
def parse_boolean(b):
    if b == False or b == True:
        return b
    b = b.strip()
    if len(b) < 1:
        return False
    b = b[0].lower()
    if b == 't' or b == '1' or b == 'y':
        return True
    return False

def new_server_key():
    return 'Server_' + generate_string()

def new_account_key():
    return 'Account_' + generate_string()
    
def current_account():
    user = users.get_current_user()
    
    account = Account.all().filter("user =", user).get()
      
    if account is None:
      account = Account(key_name = new_account_key(), user = user)
      db.put(account)    
	  
    return account

def server_success(ip_address):
    server = AppServer.all().filter("ip_address =", ip_address).filter("active =", True).get()
    db.run_in_transaction(_success_transaction, server.key(), datetime.utcnow())

def _success_transaction(key, date):
    server = db.get(key)
    if server is None:
        return
    server.success_count += 1
    server.last_success_date = date
    server.put()

def server_failure(ip_address):
    server = AppServer.all().filter("ip_address =", ip_address).filter("active =", True).get()
    db.run_in_transaction(_failure_transaction, server.key(), datetime.utcnow())

def _failure_transaction(key, date):
    server = db.get(key)
    if server is None:
        return
    server.failure_count += 1
    server.last_failure_date = date
    server.put()       

class Account(db.Model):
  user = db.UserProperty(required = True)
  created = db.DateTimeProperty(auto_now_add = True)

class AppServer(db.Model):
    name = db.StringProperty(required = True)
    owner = db.ReferenceProperty(Account, required = True)
    ip_address = db.StringProperty(required = True)  
    created = db.DateTimeProperty(auto_now_add = True)
    active = db.BooleanProperty(default = True)

    success_count = db.IntegerProperty(default = 0)
    last_success_date = db.DateTimeProperty()
    failure_count = db.IntegerProperty(default = 0)
    last_failure_date = db.DateTimeProperty()
